<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
//Api工具类
import * as apiUtil from "@/api/ApiUtils"
//Api接口和类
import {SysChineseColorVO,apiSave,apiGetDetail} from "@/api/SysChineseColorApi"

// Props 和 Emits
const props = defineProps<{
  dataId: number | null
}>();

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'successed'): void
}>();

/**
 * 表单数据
 */
const formData = ref<SysChineseColorVO>(new SysChineseColorVO())

/**
 * 数据验证规则
 */
const rules = {
 colorName:[{ required: true, message: '颜色名称必填!' }],
 colorValue:[{ required: true, message: '颜色值必填!' }],
}

/**
 * 操作类型
 */
const actionType = computed(() => {
  return props.dataId ? "修改" : "添加"
})

/**
 * 页面加载后执行的钩子函数
 */
onMounted(() => {
    if (props.dataId) {
      handleGetDetail();
    } else {
      formData.value = new SysChineseColorVO();
    }
})

/**
 * 保存数据
 */
const handleSave = async () => {
  try {
    const res = await apiSave(formData.value)
    if (apiUtil.isSuccessed(res)) {
      emit('successed');
      emit('close');
      apiUtil.notifySuccess(actionType.value + "成功");
    }
  } catch (error) {
    emit('close');
    apiUtil.notifyError('提交失败',error.message);
  }
}

/**
 * 查询详情
 */
const handleGetDetail = async () => {
  if (!props.dataId) return;
  try {
    const res = await apiGetDetail(props.dataId)
    if (apiUtil.isSuccessed(res)) {
      // 保留响应式连接的更新方式
      formData.value = res.data;
    }
  } catch (error) {
    apiUtil.notifyError('查询失败',error.message);
  }
}
</script>

<template>
  <div>
    <a-form
        :model="formData"
        name="basic"
        autocomplete="off"
        @finish="handleSave"
        :label-col="{ span: 3 }"
    >

           <a-form-item label='颜色名称'  name='colorName' :rules='rules.colorName' >
               <a-input v-model:value='formData.colorName' />
           </a-form-item>
           <a-form-item label='分类编号'  name='typeCode' >
               <a-input v-model:value='formData.typeCode' />
           </a-form-item>
           <a-form-item label='颜色值'  name='colorValue' :rules='rules.colorValue' >
               <a-input v-model:value='formData.colorValue' />
           </a-form-item>

      <a-row>
        <a-col :offset="18" :span="3">
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-col>
        <a-col>
          <a-button @click="emit('close')">取消</a-button>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<style scoped>
</style>
